<template>
  <div class="groupMembers">
    <authTable
      ref="groupMemberTable"
      v-loading="loading"
      :table-opts="tableOpts"
      :is-column-search="false"
      :pagination-data="{
        total: total,
        queryParams: filterForm,
      }"
      @pagination="pagination"
      @searchReset="handleReset"
      @searchChange="handleQuery"
      @selection-change="selectionChange"
    >
      <template #toolbarBtn>
        <el-input
          v-model.trim="realName"
          placeholder="请输入姓名"
          style="width: 280px"
          size="small"
          clearable
          maxlength="30"
          @keyup.enter.native="handleQuery"
          @clear="handleReset"
        />
        <div class="btnGroup">
          <el-button
            v-permission="['ADMINMEMBERS_ADD_BUTTON']"
            size="small"
            type="primary"
            :disabled="groupInfo.admingroupParentId === '-1' || $store.state.user.groupId === groupInfo.admingroupId"
            @click="handleAddPerson"
          >添加成员</el-button>
          <el-button v-permission="['ADMINMEMBERS_BATCHREMOVE_BUTTO']" size="small" :disabled="groupInfo.admingroupParentId === '-1' || $store.state.user.groupId === groupInfo.admingroupId"
                     @click="batchRemove()">批量移除</el-button>
        </div>
      </template>
      <template #realName="realNameTable">
        <el-popover
          trigger="click"
          placement="right"
          width="320"
          popper-class="popoverClass"
        >
          <personCard
            v-if="realNameTable.param.userId === personId"
            :ref="realNameTable.param.userId"
            :person-id="personId"
          />
          <span
            slot="reference"
            style="cursor: pointer;text-decoration: underline;"
            @click="nameCardClick(realNameTable.param)"
          >
            {{ realNameTable.param.realName }}
          </span>
        </el-popover>
      </template>
      <!-- <template v-slot:realName="realName">
        <div class="realNameDiv" @click="nameCardClick(realName.param)">
          <el-avatar size="small">
            <span>{{ realName.param.realName.substr(-1) }}</span>
          </el-avatar>
          <span>{{ realName.param.realName }}</span>
        </div>
      </template>
      <template v-slot:createUser="createUser">
        <div class="createUserDiv">
          <el-avatar size="small">
            <span>{{ createUser.param.createUser.substr(-1) }}</span>
          </el-avatar>
          <span class="realname">{{ createUser.param.createUser }}</span>
        </div>
      </template> -->
    </authTable>
    <personSelect ref="personSelect" :api="addPersonApi" title="添加管理员"
                  @handleSelectData="selectOk" />
    <!-- <personCard v-if="cardShow" :person-id="personId" @closeCard="closeCard" /> -->
  </div>
</template>
<script>
import adminManageApi from '@/framework/api/authCenter/adminManage/adminManage'
import personCard from '@/framework/components/auth-coms/authCard/index.vue'
import addPersonApi from '@/framework/api/addPerson'

export default {
  components: { personCard },
  props: {
    groupInfo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    groupId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      addPersonApi,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 用户组织机构关联表格数据
      list: [],
      // 查询参数
      filterForm: {
        admingroupId: '',
        account: '',
        realName: '',
        groupId: '',
        pageNo: 1,
        pageSize: 10
      },
      tableOpts: {
        rowKey: 'userId',
        tableData: [],
        toolbarBtn: [],
        customSearch: [{}],
        'is-show-column': true,
        // 表格第一列
        firstTableCol: {
          select: true,
          width: 55,
          type: 'selection'
        },
        tableCol: [
          {
            prop: 'account',
            label: '账号',
            show: true,
            search: true,
            align: 'left'
          },
          {
            prop: 'realName',
            label: '姓名',
            show: true,
            slotName: 'realName',
            align: 'left'
          },
          {
            prop: 'orgName',
            label: '所属组织',
            show: true,
            align: 'left'
          },
          {
            prop: 'createUser',
            label: '创建人',
            show: true,
            // slotName: "createUser",
            align: 'left'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            show: true,
            align: 'left',
            type: 'date'
            // disabled: true,
          }
        ],
        operator: {
          // width: 90,
          align: 'left',
          operatorBtn:
            this.$store.getters.orgId !== this.groupId
              ? [
                {
                  text: '移除',
                  permission: ['ADMINMEMBERS_DEL_BUTTON'],
                  size: 'small',
                  type: 'danger',
                  disabledChange: () => {
                    return this.groupInfo.admingroupParentId === '-1' || this.$store.state.user.groupId === this.groupInfo.admingroupId
                  },
                  click: (row, col, cellValue) => {
                    return this.removeMembers(row)
                  }
                }
              ]
              : []
        }
      },
      realName: '',
      selectionRow: [],
      personId: ''
      // cardShow: false,
    }
  },
  watch: {
    groupId(val) {
      this.groupId = val
    },
    realName(newVal, oldVal) {
      this.filterForm.realName = newVal
      this.getList()
    }
  },
  created() {
    // this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      this.filterForm.admingroupId = this.groupId
      adminManageApi.getManagerUserPage(this.filterForm).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery(formModel) {
      if (this.realName.length > 30) {
        this.$dtMessage({ message: '不能超过30个字符！', type: 'error' })
        return
      }
      this.filterForm = { ...this.filterForm, ...formModel }
      this.filterForm.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.filterForm = {
        account: '',
        realName: '',
        statusFlag: '',
        pageNo: 1,
        pageSize: 10
      }
      this.realName = ''
      this.handleQuery()
    },
    pagination() {
      this.getList(this.filterForm)
    },
    selectionChange(val) {
      this.selectionRow = val
    },
    batchRemove() {
      if (this.selectionRow.length === 0) {
        this.$dtMessage({ message: '请先选择要移除的人员!', type: 'error' })
      } else {
        this.$dtMessageBox({
          title: '提示',
          message: '是否确认批量移除?',
          type: 'warning'
        }).then(() => {
          this.loading = true
          const userIds = this.selectionRow.map((res) => res.userId).join(',')
          adminManageApi
            .delMember({
              groupId: this.groupId,
              userIds
            })
            .then((res) => {
              this.$dtMessage({ message: res.message, type: 'success' })
              this.$refs.groupMemberTable.clearSelection()
              this.getList()
            }).catch(() => {
              this.loading = false
            })
        })
      }
    },
    removeMembers(val) {
      this.$dtMessageBox({
        title: '提示',
        message: `是否确认移除“${val.realName}”?`,
        type: 'warning'
      }).then(() => {
        this.loading = true
        adminManageApi
          .delMember({
            groupId: this.groupId,
            userIds: val.userId
          })
          .then((res) => {
            this.$dtMessage({ message: res.message, type: 'success' })
            this.getList()
          }).catch(() => {
            this.loading = false
          })
      })
    },
    handleAddPerson() {
      if (this.$store.getters.orgId === this.groupId) {
        this.$dtMessage({
          message: '不可以往本组添加管理员！',
          type: 'error'
        })
        return
      }
      this.$refs.personSelect.show()
    },
    selectOk(val) {
      this.loading = true
      adminManageApi
        .saveManagerUser({
          groupId: this.groupId,
          userIds: val.map((res) => res.userId).join(',')
        })
        .then((res) => {
          if (res.success) {
            this.loading = false
            this.$dtMessage({ message: res.message, type: 'success' })
            this.getList()
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    nameCardClick(val) {
      this.personId = val.userId
      // this.cardShow = true;
    }
    // closeCard() {
    //   this.cardShow = false;
    // },
  }
}
</script>
<style scoped lang="scss">
.groupMembers {
  animation: groupMembers 1s 1;
}

@keyframes groupMembers {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

.btnGroup {
  flex: 1;
  margin-right: 16px;

  button {
    margin-bottom: 0 !important;
    margin-left: 16px;
    float: right;
  }
}

.realNameDiv {
  cursor: pointer;
  height: 24px;
  background: #ebeef5;
  border-radius: 100px;
  padding: 2px 8px 2px 2px;
  width: fit-content;
  display: flex;
  align-items: center;

  ::v-deep .el-avatar--small {
    margin-right: 2px;
    width: 20px;
    height: 20px;
    background: linear-gradient(180deg, #b8e24b 0%, #129a37 100%);
    position: relative;

    span {
      display: inline-block;
      color: #ffffff;
      font-size: 12px;
      transform-origin: 0 0;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}

.createUserDiv {
  display: flex;
  align-items: center;

  ::v-deep .el-avatar--small {
    width: 28px;
    height: 28px;
    background: linear-gradient(180deg, #b8e24b 0%, #129a37 100%);
    margin-right: 8px;
  }
}
</style>
